package com.dhl.rabbitmq.eight;

import com.dhl.rabbitmq.utils.RabbitConstant;
import com.dhl.rabbitmq.utils.RabbitUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

import static com.dhl.rabbitmq.utils.RabbitConstant.*;

/**
 * @author danghailiang
 * 死信实战 消费者
 */
public class Consumer01 {
    /**
     * 普同交换名称
     */
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    /**
     * 普同队列名称
     */
    public static final String NORMAL_QUEUE = "normal_queue";
    /**
     * 死信交换名称
     */
    public static final String DEAD_EXCHANGE = "dead_exchange";
    /**
     * 死信队列名称
     */
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        // 获取信道
        Channel channel = RabbitUtils.getChannel();


        // 声明死信交换
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        // 声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        // 死信队列，绑定交换
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, DEAD_ROUTING_KEY);
        //===================================================================================================


        // 声明普通交换
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        // 设置死信队列map集合
        Map<String, Object> arguments = new HashMap<>(2);
        // 绑定死信交换
        arguments.put(RabbitConstant.X_DEAD_LETTER_EXCHANGE, DEAD_EXCHANGE);
        // 绑定路由key
        arguments.put(RabbitConstant.X_DEAD_LETTER_ROUTING_KEY, DEAD_ROUTING_KEY);
        // 设置队列存储消息最大长度，超过该长度转发给死信队列， 测试时间限制和拒绝策略时候注销改行
        // arguments.put(X_MAX_LENGTH,6);
        // 声明普通队列,
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        // 普通队列，绑定交换
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, NORMAL_ROUTING_KEY);
        // 接受消息
        System.out.println("等待接收消息.....");
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            if("info: 5".equals(message)){
                // 通过标识拒绝应答，并且不放回原队列
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(),false);
                System.out.println("Consumer01 接收到消息" + message +"：：：被拒绝的消息");
            }else{
                // 接受应答,并且关闭批量应答
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                System.out.println("Consumer01 接收到消息" + message);
            }


        };
        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, consumerTag -> {
        });
    }
}
